try:
	import sys
	import os
	import pygame
	import logging
	import ConfigParser

	from socket import *
	from pygame.locals import *

	import utils

	import game.world
	import game.map
	import game.unit
	import game.job

	import ui.pointer
	import ui.container
	import ui.mapview
	import ui.console
	import ui.window
	
except ImportError, message:
	print "Could not load module %s" % (message)
	sys.exit(2)

WINDOW_TITLE = "fortress"

class GameApp(ui.container.Container):
	def __init__(self):
		self.log = logging.getLogger("fortress")
		self.loadConfig()

		pygame.init()

		self.screenWidth = self.config.getint("ui", "width")
		self.screenHeight = self.config.getint("ui", "height")

		self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight))
		pygame.display.set_icon(utils.load_image("icon.png"))
		pygame.display.set_caption(WINDOW_TITLE)

		self.pointer = ui.pointer.Pointer("pointer.png")
		self.font = pygame.font.Font(os.path.join("data", "fonts", self.config.get("ui", "font")), 12)

		ui.container.Container.__init__(self, 0, 0, self.screenWidth, self.screenHeight)

	def loadConfig(self):
		configFileName = "config.ini"
		self.config = ConfigParser.SafeConfigParser()
		self.config.read(configFileName)

	def runGame(self):
		self.gameWorld = game.world.World()
		self.gameWorld.generate()

		self.tileView = ui.mapview.TileMapView(0, 0, self.screenWidth, self.screenHeight, self.gameWorld)
		self.consoleWindow = ui.console.ConsoleWindow(10, 10, 200, 200, self.font)
		self.consoleWindow.hide()

		self.add(self.tileView)
		self.add(self.consoleWindow)

		handler = ui.console.ConsoleHandler(self.consoleWindow.console)
		self.log.addHandler(handler)
		self.log.setLevel(logging.DEBUG)

		self.clock = pygame.time.Clock()
		self.running = True
		self.paused = False
		while self.running:
			# tick the clock and try to maintain 60 fps
			self.clock.tick()
			
			if not self.paused:
				self.gameWorld.update()

			# event loop
			for event in pygame.event.get():
				if not self.handleEvent(event):
					if event.type == QUIT:
						self.onQuit()

			# update our mouse pointer sprite
			self.pointer.update()

			self.screen.fill((255, 0, 255))
			
			self.draw(self.screen)

			# get our FPS and put it into a surface so we can write it to the screen
			fpsMessage = "FPS: %s" % (round(self.clock.get_fps(), 2))
			fpsMessageSurface = self.font.render(fpsMessage, 1, (255, 255, 255))
			self.screen.blit(fpsMessageSurface, (self.screenWidth - fpsMessageSurface.get_width(), self.screenHeight - fpsMessageSurface.get_height()))

			# put a paused message on the screen when we are paused
			if self.paused:
				pausedMessage = "* PAUSED *"
				pausedMessageSurface = self.font.render(pausedMessage, 1, (255, 255, 255))
				self.screen.blit(pausedMessageSurface, ((self.screenWidth - pausedMessageSurface.get_width()) / 2, (self.screenHeight - pausedMessageSurface.get_height()) / 2))

			# draw the mouse pointer
			self.pointer.draw(self.screen)
			
			pygame.display.flip()

	def onQuit(self):
		self.running = False

	def onMouseButtonUp(self, event):
		if event.button == 1:
			# left mouse button
			x = event.pos[0] / 32
			y = event.pos[1] / 32
			self.gameWorld.jobList.append(game.job.Job("test", (x, y)))
			self.log.info("add job (%s, %s)" % (x, y))
		
		return True
	
	def onKeyDown(self, event):
		if event.key == pygame.K_ESCAPE:
			self.running = False
		if event.key == pygame.K_SPACE:
			# toggle the pause on and off
			self.paused = not self.paused
		if event.key == pygame.K_BACKQUOTE:
			if self.consoleWindow.isVisible():
				self.consoleWindow.hide()
			else:
				self.consoleWindow.show()
		
		return True

	def cleanUp(self):
		pygame.quit()

def main():
	gameApp = GameApp()
	gameApp.runGame()
	gameApp.cleanUp()

if __name__ == '__main__':
	main()
